package com.chaodev.base.utils;

import cn.afterturn.easypoi.csv.entity.CsvImportParams;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author lccccc
 */
public class FileUtils {

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) {
        ExportParams exportParams;
        String[] type = fileName.split("\\.");
        if ("xls".equals(type[type.length - 1])) {
            exportParams = new ExportParams(title, sheetName, ExcelType.HSSF);
        } else {
            exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        }
        // 标题
        exportParams.setHeaderHeight(800D);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    // 以对象list导出
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
        // 获取后缀名
        String[] type = fileName.split("\\.");
        if ("xls".equals(type[type.length - 1])) {
            defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.HSSF));
        } else {
            defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
        }
    }

    // 以map list导出
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        defaultExport(list, fileName, response);
    }

    // this
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
        // ExcelType.XSSF --> .xlsx
        // ExcelType.HSSF --> .xls
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        if (workbook != null) ;
        downLoadExcel(fileName, response, workbook);
    }

    public static void exportTxt(HttpServletResponse response, String text, String fileName) {
        try {
            response.setCharacterEncoding("utf-8");
            //设置响应的内容类型
            response.setContentType("text/plain");
            //设置文件的名称和格式
            response.addHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
            BufferedOutputStream buff = null;
            ServletOutputStream outStr = null;
            try {
                outStr = response.getOutputStream();
                buff = new BufferedOutputStream(outStr);
                buff.write(text.getBytes("UTF-8"));
                buff.flush();
                buff.close();
            } catch (Exception e) {
                System.out.println("e.getMessage().toString() = " + e.getMessage().toString());
            } finally {
                try {
                    buff.close();
                    outStr.close();
                } catch (Exception e) {
                    System.out.println("e.getMessage().toString() = " + e.getMessage().toString());
                }
            }
        } catch (Exception e) {
            System.out.println("e.getMessage().toString() = " + e.getMessage().toString());
        }
    }

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            //throw new NormalException(e.getMessage());
        }
    }

    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        // ExcelType.XSSF --> .xlsx
        // ExcelType.HSSF --> .xls
        String[] type = fileName.split("\\.");
        Workbook workbook;
        if ("xls".equals(type[type.length - 1])) {
            workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        } else {
            workbook = ExcelExportUtil.exportExcel(list, ExcelType.XSSF);
        }
        if (workbook != null) ;
        downLoadExcel(fileName, response, workbook);
    }

    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if ("".equals(filePath) || filePath == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            //throw new NormalException("模板不能为空");
            System.out.println("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            //throw new NormalException(e.getMessage());
        }
        return list;
    }

    // csv导入，重新写的导入方法，可以返校验结果
    public static <T> ExcelImportResult<T> importCsv(InputStream inputstream, Class<?> pojoClass, CsvImportParams params) {
        return readExcel(inputstream, pojoClass, params);
    }

    private static ExcelImportResult readExcel(InputStream inputstream, Class<?> pojoClass, CsvImportParams params) {
        ExcelImportResult importResult = new ExcelImportResult();
        List collection = new ArrayList();
        List failCollection = new ArrayList();
        return importResult;
    }

    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (NoSuchElementException e) {
            //throw new NormalException("excel文件不能为空");
        } catch (Exception e) {
            //throw new NormalException(e.getMessage());
        }
        return list;
    }
}
